package com.hxzy;

import ch.qos.logback.core.net.server.Client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

public class SocketServer {
    /**
     * 黎高源1asdsasd
     */

    //存放线上用户(test)pijiojiyguljnjlnkj
    public static ConcurrentHashMap<String,Socket>  socketMap=new ConcurrentHashMap<>();

    public static void main(String[] args) throws IOException {

        //1、开启服务，绑定本机端口
        ServerSocket  serverSocket=new ServerSocket(10086);
        System.out.println("服务器启动成功......");

        while(true){
           //2、监听客户端连接(阻塞式的)
            Socket  socket= serverSocket.accept();

            //放到全局变量中
            socketMap.put(socket.getInetAddress().getHostAddress().toString(),socket);

            //3、开启一个线程处理客户端操作
            ClientThread  ct=new ClientThread(socket);
            //启动线程
            ct.start();

            System.out.println(socket.getInetAddress().toString()+",进来了");
        }
    }


   static class ClientThread extends Thread{

        private Socket clientSocket;

        public ClientThread(Socket clientSocket){
            this.clientSocket=clientSocket;
        }

       @Override
       public void run() {

           try {
               //读取客户端发过来的消息
               /*
                 //功能菜单
                System.out.println("1、向客户发消息");
                  System.out.println("2、退出");
                */

               BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
               String str="";
               while( (str=br.readLine())!=null){
                   System.out.println(this.clientSocket.getInetAddress().toString()+",说："+str);
               }
               //关闭输入流
               this.clientSocket.shutdownInput();
               //建立输出流
               PrintWriter pw = new PrintWriter(this.clientSocket.getOutputStream());
               pw.write("server say hi");
               pw.flush();

               //输入流
               br.close();
               pw.close();

               //移出
               socketMap.remove(this.clientSocket.getInetAddress().toString());
               this.clientSocket.close();


           } catch (IOException e) {
               e.printStackTrace();
           }
       }
   }
}
